<?php
session_start();

$con = mysqli_connect("localhost", "root", NULL, "csproj2");
if (mysqli_connect_errno()) {
	printf("Connect failed: %s", mysqli_connect_error());
	exit();
}

$con2 = mysqli_connect("localhost", "root", NULL, "csproj2");
if (mysqli_connect_errno()) {
	printf("Connect failed: %s", mysqli_connect_error());
	exit();
}

//handle user actions
if (isset($_SESSION['user'])) {

	//user rating
	if (isset($_POST['rateVal']) && isset($_POST['rateCid'])) {
		$stmt = $con->prepare("SELECT p_id FROM rate WHERE p_id = ? AND c_id = ?");
		$stmt->bind_param('ss', $_SESSION['user'], $_POST['rateCid']);
		$stmt->execute();
		$stmt->bind_result($user);
		$stmt->fetch();
		$stmt->close();
		
		//already rated
		if ($user == $_SESSION['user']) {
			$stmt = $con->prepare("UPDATE rate SET rate = ? WHERE c_id = ? AND p_id = ?");
			$stmt->bind_param('sss', $_POST['rateVal'], $_POST['rateCid'], $user);
			$stmt->execute();
			$stmt->close();
		} else {
		//new rating
			$stmt = $con->prepare("INSERT INTO rate VALUES(?, ?, ?)");
			$stmt->bind_param('sss', $_SESSION['user'], $_POST['rateCid'], $_POST['rateVal']);
			$stmt->execute();
			$stmt->close();
		}
	}

	$newCid = NULL;
	//create new content
	if (isset($_POST['createContent']) && isset($_POST['createTopics'])) {
		$createTopics = explode(",", htmlspecialchars($_POST['createTopics']));
		//fetch highest cid to use for inserts
		$stmt = $con->prepare("SELECT c_id FROM content ORDER BY c_id DESC");
		$stmt->execute();
		$stmt->bind_result($cidHigh);
		$stmt->fetch();
		$stmt->close();

		$cidHigh = intval($cidHigh) + 1;
		$newCid = $cidHigh;

		$stmt = $con->prepare("INSERT INTO content VALUES(?, ?, 0, ?, NOW())");
		$stmt->bind_param('iss', $cidHigh, htmlspecialchars(trim($_POST['createContent'])), $_SESSION['user']);
		$stmt->execute();
		$stmt->close();

		for ($i = 0; $i < count($createTopics); $i++) {
			$stmt = $con->prepare("INSERT INTO topic VALUES(?, ?)");
			$stmt->bind_param('is', $cidHigh, $createTopics[$i]);
			$stmt->execute();
			$stmt->close();
		}
	}

	//create new circle
	if (isset($_POST['circName']) && isset($_POST['circDesc'])) {
		$name = htmlspecialchars(trim($_POST['circName']));
		$desc = htmlspecialchars(trim($_POST['circDesc']));

		$stmt = $con->prepare("SELECT circle_name FROM circle WHERE circle_name = ? AND owner_id = ?");
		$stmt->bind_param('ss', $name, $_SESSION['user']);
		$stmt->execute();

		$stmt->bind_result($bExist);
		$stmt->fetch();
		$stmt->close();

		$bExist = isset($bExist);
		if (!$bExist) {
			$stmt = $con->prepare("INSERT INTO circle VALUES(?, ?, ?)");
			$stmt->bind_param('sss', $_SESSION['user'], $name, $desc);
			$stmt->execute();

			$stmt->close();

			$stmt = $con->prepare("INSERT INTO incirc VALUES(?, ?, ?)");
			$stmt->bind_param('sss', $_SESSION['user'], $name, $_SESSION['user']);
			$stmt->execute();

			$stmt->close();
		}
	}

	//add member to circle
	if (isset($_POST['circMember']) && isset($_POST['circChoice'])) {
		$member = htmlspecialchars(trim($_POST['circMember']));
		$circle = htmlspecialchars(trim($_POST['circChoice']));

		//check that given member exists
		$stmt = $con->prepare("SELECT p_id FROM person WHERE p_id = ?");
		$stmt->bind_param('s', $member);
		$stmt->execute();

		$stmt->bind_result($bUserExist);
		$stmt->fetch();
		$stmt->close();

		$bUserExist = isset($bUserExist);
		if ($bUserExist) {
			//check user not already in circle
			$stmt = $con->prepare("SELECT p_id FROM incirc WHERE circle_name = ? AND owner_id = ? AND p_id = ?");
			$stmt->bind_param('sss', $circle, $_SESSION['user'], $member);
			$stmt->execute();

			$stmt->bind_result($bExist);
			$stmt->fetch();
			$stmt->close();

			$bExist = isset($bExist);
			if (!$bExist) {
				$stmt = $con->prepare("INSERT INTO incirc VALUES(?, ?, ?)");
				$stmt->bind_param('sss', $_SESSION['user'], $circle, $member);
				$stmt->execute();

				$stmt->close();
			}
		}
	}

	//restrict circle visiblity
	if (isset($_POST['circRestrict']) && strlen($_POST['circRestrict']) > 0 && (isset($_POST['circCid']) || isset($newCid))) {
		$circle = htmlspecialchars(trim($_POST['circRestrict']));
		if (isset($_POST['circCid'])) {
			$cid = htmlspecialchars(trim($_POST['circCid']));
		} else if (isset($newCid)) {
			$cid = $newCid;
		}

		//check that given content exists
		$stmt = $con->prepare("SELECT c_id FROM visible WHERE c_id = ? AND circle_name = ? AND owner_id = ?");
		$stmt->bind_param('sss', $cid, $circle, $_SESSION['user']);
		$stmt->execute();

		$stmt->bind_result($bExist);
		$stmt->fetch();
		$stmt->close();

		$bExist = isset($bExist);
		if (!$bExist) {
			$stmt = $con->prepare("INSERT INTO visible VALUES(?, ?, ?)");
			$stmt->bind_param('sss', $_SESSION['user'], $circle, $cid);
			$stmt->execute();

			$stmt->close();

			$stmt = $con->prepare("UPDATE content SET privacy = 1 WHERE c_id = ?");
			$stmt->bind_param('s', $cid);
			$stmt->execute();

			$stmt->close();
		}

	}

	//find circles user is in
	$stmt = $con->prepare("SELECT owner_id, circle_name, description FROM incirc NATURAL JOIN circle WHERE p_id = ?");
	$stmt->bind_param('s', $_SESSION['user']);
	$stmt->execute();

	$stmt->bind_result($owner, $circname, $desc);
	$circowners = array();
	$circles = array();
	$circdescs = array();

	while ($stmt->fetch()) {
		$owner = htmlspecialchars($owner);
		$circname = htmlspecialchars($circname);
		$desc = htmlspecialchars($desc);

		array_push($circowners, $owner);
		array_push($circles, $circname);
		array_push($circdescs, $desc);
	}
	$stmt->close();
	
}

?>

<html>
<head>
<title>ShareCon - A Content Sharing Site</title>
</head>

<body>
<div id="main" style="padding-left:10%; padding-right:10%">
<div id="inner" style="padding:5%">
<div id="header" style="text-align:center; padding-bottom:5%; border-bottom:1px solid black">
<h1><a style='color:black; text-decoration:none' href='/index.php'>ShareCon - A Content Sharing Site</a></h1>
</div>
<br>



<div id="content" style="display:inline-block; width:80% ;border-right:1px dashed black; padding-right:2%;">
<?php
	$bAction = isset($_GET['action']) && isset($_SESSION['user']);
	if ($bAction)
		$action = strtolower(trim($_GET['action']));

	if ($bAction && $action == 'create') {
		echo "<a href='/index.php'>Go back</a>";
		echo "<h3>Creating new content...</h3>";
	} else if ($bAction && $action == 'circle') {
		echo "<a href='/index.php'>Go back</a>";
		echo "<h3>Circle Management...</h3>";
	} else {
		echo "<h3>Here is the latest content...</h3>";
	}

	$visibleCids = array();
	$visibleTopics = array();

	if (isset($_SESSION['user']) && count($circles) > 0) {
		/* query looks for all visible content
		 * and pulls from q2 to get author name
		 * orders by newest first (highest c_id)
		 */
		$stmt = $con->prepare("SELECT DISTINCT q2.c_id, q2.c_text, q2.owner_id, q2.p_time, q2.fname, q2.lname, q2.privacy FROM
			(SELECT content.c_id FROM content LEFT JOIN visible
			ON (content.c_id = visible.c_id)
			LEFT JOIN incirc
			ON (visible.owner_id = incirc.owner_id
			AND visible.circle_name = incirc.circle_name)
			WHERE (p_id = ? AND privacy = 1) OR privacy = 0) AS q1,

			(SELECT *
			FROM content LEFT JOIN person
			ON (content.owner_id = person.p_id)) AS q2
			
			WHERE q1.c_id = q2.c_id
			ORDER BY q2.c_id DESC");
		

		$stmt->bind_param('s', $_SESSION['user']);
		
	} else {
		//guest user
		$stmt = $con->prepare("SELECT c_id, c_text, owner_id, p_time, fname, lname, privacy
			FROM content NATURAL JOIN person
			WHERE owner_id = p_id AND privacy = 0
			ORDER BY c_id DESC");
	}

	$stmt->execute();
	$stmt->bind_result($cid, $ctext, $owner, $time, $fname, $lname, $privacy);

	while ($stmt->fetch()) {

		//body of content post
		$cid = htmlspecialchars($cid);
		$ctext = htmlspecialchars($ctext);
		$owner = htmlspecialchars($owner);
		$time = htmlspecialchars($time);
		$fname = htmlspecialchars($fname);
		$lname = htmlspecialchars($lname);

		if (!in_array($cid, $visibleCids)) {
			array_push($visibleCids, $cid);
		}
		$ctopics = array();
		
		$s2 = $con2->prepare("SELECT topic FROM topic NATURAL JOIN content WHERE c_id = ?");
		$s2->bind_param('s', $cid);

		$s2->execute();
		$s2->bind_result($topic);

		while ($s2->fetch()) {
			$topic = htmlspecialchars($topic);
			array_push($ctopics, $topic);

			//populate all distinct topics
			if (!in_array($topic, $visibleTopics)) {
				array_push($visibleTopics, $topic);
			}
		}
		$s2->close();



		//display content
		//if no set action or action is not create/circle management
		//AND
		//((set action and topic in visible topics)
		//	OR
		//(topic is not set))
		if ((!$bAction || ($bAction && ($action != 'create' && $action != 'circle')))
			&& ((isset($_GET['topic']) && in_array(htmlspecialchars(trim($_GET['topic'])), $ctopics))
			|| !isset($_GET['topic']))) {

			printf("<div style='border-top:1px dashed black'><br>
				<span style='font-size:120%%; font-weight:bold'>#%s: %s (%s %s) wrote...</span><br>
				<span style='font-size:80%%'>%s</span>
				<br><br>
				<span style='font-size:110%%; padding-left'>%s</span><br><br>",
				$cid, $owner, $fname, $lname, $time, $ctext);

			
			//fetch circle visibility
			$visibleCircles = array();
			if ($privacy == 1) {
				$s2 = $con2->prepare("SELECT circle_name FROM visible WHERE c_id = ?");

				$s2->bind_param('s', $cid);
				$s2->execute();

				$s2->bind_result($circle);
				if ($s2->fetch()) {
					printf("<span style='font-size:80%%'>Circles: ");
					printf("%s", $circle);
					array_push($visibleCircles, $circle);
				}
				while ($s2->fetch()) {
					printf(", %s", $circle);
					array_push($visibleCircles, $circle);
				}
				$s2->close();

				printf("</span><br>");

			}

			//restrict visibility
			if (isset($_SESSION['user']) && $owner == $_SESSION['user']) {
				$q = array_count_values($circowners);
				if (isset($q[$_SESSION['user']]) && $q[$_SESSION['user']] > 0) {
					printf("<span style='font-size:80%%'>Restrict to: </span>");

					printf("<form method='post' action='/index.php'>
						<select name='circRestrict'>");

					for ($i = 0; $i < count($circles); $i++) {
						if ($circowners[$i] == $_SESSION['user'] && !in_array($circles[$i], $visibleCircles)) {
							printf("<option value='%s' style='font-size:80%%'>%s</option>", $circles[$i], $circles[$i]);
						}
					}

					printf("</select><input type='hidden' name='circCid' value='%s' />
						<input type='submit' value='Go' style='font-size:80%%' /></form>", $cid);
				}
			}
			

			//fetch content topics
			printf("<span style='font-size:80%%'>Topics: ");
			if (count($topic) > 0) {
				for ($i = 0; $i < count($ctopics); $i++) {
					if ($i == 0) {
						printf("%s", $ctopics[$i]);
					} else {
						printf(", %s", $ctopics[$i]);
					}
				}
			} else {
				printf("none");
			}
			printf("</span><br>");

			//fetch content rating
			$s2 = $con2->prepare("SELECT AVG(rate) 
				FROM `content` NATURAL JOIN `rate`
				WHERE c_id = ?
				GROUP BY c_id");

			$s2->bind_param('s', $cid);
			$s2->execute();

			$s2->bind_result($rtg);
			$s2->fetch();
			$s2->close();

			//allow user rating
			printf("<span style='font-size:80%%'>Rating: ");
			if ($rtg != NULL) {
				$rtg = floatval(htmlspecialchars($rtg));
				printf("%0.2f", $rtg);
			} else {
				printf("-");
			}
			if (isset($_SESSION['user'])) {
				printf("<br><form method='post' action='/index.php'>
					<select name='rateVal' style='font-size:80%%'>
					<option value='-2'>-2</option>
					<option value='-1'>-1</option>
					<option value='0' selected>0</option>
					<option value='1'>1</option>
					<option value='2'>2</option>
					</select>
					<input type='hidden' name='rateCid' value='%s' />
					<input type='submit' value='Rate' style='font-size:80%%' /></form>",
					$cid);
			}
			printf("</span></div><br>");
		}
	}

	//handle action areas
	if ($bAction && $action == 'create') {

		printf("<table><form method='post' action='/index.php'>
			<tr><td><textarea name='createContent' rows='15' cols='75'></textarea></td></tr>
			<tr><td>Content topics, seperated by commas ( , ):
			<input type='text' name='createTopics' /></td></tr>");

		$q = array_count_values($circowners);
		if (isset($q[$_SESSION['user']]) && $q[$_SESSION['user']] > 0) {
			printf("<tr><td>Restrict to: ");

			printf("<select name='circRestrict'>
				<option value='' selected>---</option>");

			for ($i = 0; $i < count($circles); $i++) {
				if ($circowners[$i] == $_SESSION['user'] ) {
					printf("<option value='%s'>%s</option>", $circles[$i], $circles[$i]);
				}
			}

			printf("</select></td></tr>");
		}

		printf("<tr><td><input type='submit' value='Post content' style='float:right' /></td></tr></table>
			</form>");
	} else if ($bAction && $action == 'circle') {

		printf("<span style='text-decoration:underline; font-size:120%%'>Circles you are in:</span><br>");
		$q = count($circles);
		if ($q > 0) {
			for ($i = 0; $i < $q; $i++) {
				printf("%s (%s)", $circles[$i], $circowners[$i]);
				if ($circdescs[$i] != NULL) {
					printf("<span style='color:grey'> - %s</span>", $circdescs[$i]);
				}
				printf("<br>");

			}
			printf("<br>");
		} else {
			printf("None!<br><br>");
		}

		$q = array_count_values($circowners);
		printf("<span style='text-decoration:underline; font-size:120%%'>Circles you own:</span><br>");
		if (isset($q[$_SESSION['user']]) && $q[$_SESSION['user']] > 0) {
			for ($i = 0; $i < count($circles); $i++) {
				if ($circowners[$i] == $_SESSION['user']) {
					printf("%s", $circles[$i]);
					if ($circdescs[$i] != NULL) {
						printf("<span style='color:grey'> - %s</span>", $circdescs[$i]);
					}
					printf("<br>");
				}

			}
			printf("<br>");
			printf("<span style='text-decoration:underline; font-size:120%%'>Add member to circle:</span><br>");
			printf("<table><form method='post' action='/index.php?action=circle'>
				<tr>
					<td>Member ID:</td>
					<td><input type='text' name='circMember' /></td>
				</tr>
				<tr>
					<td>Circle:</td>
					<td><select name='circChoice' style='font-size:80%%'>");

			for ($i = 0; $i < count($circles); $i++) {
				if ($circowners[$i] == $_SESSION['user']) {
					printf("<option value='%s'>%s</option>", $circles[$i], $circles[$i]);
				}
			}

			printf("</select></td>
				</tr>
				<tr>
					<td></td>
					<td><input type='submit' value='Add member' style='float:right' /></td>
				</tr>
				</form></table><br>");
		} else {
			printf("None!<br><br>");
		}




		printf("<span style='text-decoration:underline; font-size:120%%'>Create new circle:</span><br>");
		printf("<table><form method='post' action='/index.php?action=circle'>
			<tr>
				<td>Circle name:</td>
				<td><input type='text' name='circName' /></td>
			</tr>
			<tr>
				<td>Description:</td>
				<td><input type='text' name='circDesc' /></td>
			</tr>
			<tr>
				<td></td>
				<td><input type='submit' value='Create' style='float:right' /></td>
			</tr>
			</form></table>");

	}


	$stmt->close();
?>
</div>

<div id="usercp" style="display:inline-block; width:15%; float:right;">
<span style="text-decoration:underline; font-size:110%; font-weight:bold;">User CP</span>
<br>
<?php
	if(isset($_SESSION['user'])) {
		printf("<a href='/logout.php'>Logout</a><br>");
		printf("<a href='/index.php?action=create'>Create content</a><br>");
		printf("<a href='/index.php?action=circle'>Manage circles</a><br><br>");

		printf("<span style='text-decoration:underline; font-size:110%%; font-weight:bold;'>You Are In These Circles:</span><br>");
		$q = count($circles);
		if ($q > 0) {
			for ($i = 0; $i < $q; $i++) {
				printf("%s (%s)<br>", $circles[$i], $circowners[$i]);
			}
			printf("<br>");
		} else {
			printf("None!<br><br>");
		}
	} else {
		printf("<a href='/login.php'>Login</a><br>");
		printf("<a href='/register.php'>Register</a><br><br>");
	}

	printf("<span style='text-decoration:underline; font-size:110%%; font-weight:bold;'>Visible Topics:</span><br>");
	$q = count($visibleTopics);
	if ($q > 0) {
		for ($i = 0; $i < $q; $i++) {
			$stmt = $con->prepare("SELECT AVG(rate)
				FROM `rate` NATURAL JOIN `content`
				NATURAL JOIN `topic`
				WHERE topic = ?
				GROUP BY topic");
			$stmt->bind_param('s', $visibleTopics[$i]);
			$stmt->execute();

			$stmt->bind_result($rtg);
			$stmt->fetch();
			$stmt->close();

			if ($rtg != NULL) {
				$rtg = floatval(htmlspecialchars($rtg));
				printf("<a href='/index.php?topic=%s'>%s</a> (%0.2f)<br>", $visibleTopics[$i], $visibleTopics[$i], $rtg);
			} else {
				printf("<a href='/index.php?topic=%s'>%s</a> (-)<br>", $visibleTopics[$i], $visibleTopics[$i]);
			}
		}
	} else {
		printf("None!<br>");
	}

	printf("</div>");
	$con->close();
	$con2->close();
?>
</div>

</div>
</div>
</body>
</html>
